package com.syh.jn.scm.domain.operation.entity.system;

import cn.redscarf.commons.spring.SpringContextUtils;
import com.syh.core.ddd.domain.AbstractSimpleAggregate;
import com.syh.jn.scm.domain.operation.TerminalAccountOfPhone.TerminalAccountOfPhoneDomainService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * Created by soci.song on 2018/12/13.
 * 终端手机登录账号管理
 */
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class TerminalAccountOfPhone extends AbstractSimpleAggregate<Long> {
  /**
   * 登录手机账号
   */
  private String loginPhone;
  /**
   * 登录密码
   */
  private String loginPassword;
  /**
   * 姓名
   */
  private String name;
  /**
   * 使用情况
   */
  private Short status;
  /**
   * 默认登录的关联账号
   */
  private Long defualtAccountId;
  /**
   * 绑定的账号ids
   */
  private List<Long> accountIds;
  /**
   *  所属终端系统:DOWNSTREAM,OPERATION,SUPPLIER,UPSTREAM
   */
  private String terminalType;

  public void destory() {
    //清除与账号的一对多关系
    TerminalAccountOfPhoneDomainService domainService = (TerminalAccountOfPhoneDomainService) SpringContextUtils.getBean(TerminalAccountOfPhoneDomainService.class);
    domainService.clearCorrelation(this.id);
  }

  public void binding(Long accountId) {
    //绑定手机账号与常规账号
    TerminalAccountOfPhoneDomainService domainService = (TerminalAccountOfPhoneDomainService) SpringContextUtils.getBean(TerminalAccountOfPhoneDomainService.class);
    domainService.bindingAccount(this.id,accountId);
    //如果没有默认登陆账号 则设本次绑定账号为默认登陆账号
    if (this.defualtAccountId == null) {
      this.defualtAccountId = accountId;
    }
  }

  public void untying(Long accountId) {
    TerminalAccountOfPhoneDomainService domainService = (TerminalAccountOfPhoneDomainService) SpringContextUtils.getBean(TerminalAccountOfPhoneDomainService.class);
    domainService.untyingAccount(this.id,accountId);
    //如果取消绑定的账号是默认登陆账号 则重新设置默认登陆账号
    if (this.defualtAccountId == accountId) {
      List<TerminalAccount> accounts = domainService.getAccountListByPhoneId(this.id);
      //如果没有关联账号 则停用该手机账号
      if (accounts.size() == 0 ) {
        this.defualtAccountId =null;
        this.status = -1;
        return ;
      }
      this.defualtAccountId = accounts.get(0).getId();
    }
  }

  public void enable() {
    this.status = 1;
  }

  public void disable() {
    this.status = -1;
  }
}
